package com.shujia.spark.streaming

import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.SparkSession
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Durations, StreamingContext}

object Demo5RDDToDStream {
  def main(args: Array[String]): Unit = {
    val spark: SparkSession = SparkSession
      .builder()
      .master("local[2]")
      .appName("ds")
      .config("spark.sql.shuffle.partitions", 1)
      .getOrCreate()
    import spark.implicits._

    val sc: SparkContext = spark.sparkContext

    val ssc = new StreamingContext(sc, Durations.seconds(5))

    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)

    /**
     *
     * transform: 每隔5秒传入一个rdd，在里面使用rdd的api处理数据，处理完了再返回一个rdd
     *
     */

    val resultDS: DStream[(String, Int)] = linesDS.transform((rdd: RDD[String]) => {

      //rdd的计算是一个批次内部统计，并不是全局统计
      val countRDD: RDD[(String, Int)] = rdd
        .flatMap(_.split('>'))
        .map((_, 1))
        .reduceByKey(_ + _)

      //处理完了返回一个rdd,返回的rdd会构建成新的Dstream
      countRDD
    })

    resultDS.print()


    ssc.start()
    ssc.awaitTermination()
    ssc.stop()

  }

}
